package com.csdj.t309tgspringboot.config;

import com.csdj.t309tgspringboot.service.RedisService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate,HttpSession session, HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        this.stringRedisTemplate = stringRedisTemplate;
        preHandle(session,request,response,handler);
    }

    public boolean preHandle(HttpSession session, HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取Cookie信息数组
        Cookie[] cks=request.getCookies();
        String uid="";//id
        String token="";//随机数
        if(cks!=null){
            for (Cookie cookie : cks) {
                //Cookie是以键值对的形式来保存数据的
                //可以通过键来获取相对应的值
                if("uid".equals(cookie.getName())){
                    uid=cookie.getValue();
                    session.setAttribute("uid",uid);
                }
                if("token".equals(cookie.getName())){
                    token=cookie.getValue();
                }
            }
        }else{
            response.sendRedirect("login");
            return false;
        }
        if(stringRedisTemplate.opsForValue().get(token+uid)!=null){
                if(stringRedisTemplate.opsForValue().get(token+uid)==token){
                    return true;
                }else {
                    response.sendRedirect("login");
                    return false;
                }
        }else {
            response.sendRedirect("login");
            return false;
        }
    }
}
